import { useState, useEffect, useRef } from "react";
import type { Pagination } from "@/types/api";
const defaultPagintaion = {
    current: 1,
    pageSize: 10,
};
export default function useQueryTable(props: Pagination.useQueryTableProps) {
    const [dataSource, setDataSource] = useState<any>([]);
    const [loading, setLoading] = useState(false);
    const paginationRef = useRef<Pagination.pagination>({ ...defaultPagintaion });
    const { fetchPage } = props;
    const fetch = async (params: Pagination.pagination) => {
        try {
            setLoading(true);
            const { list: data, page } = await fetchPage(params);
            setDataSource(Array.isArray(data) ? data : []);
            paginationRef.current = {
                ...paginationRef.current,
                ...page,
                current: page.pageNum,
            };
            setLoading(false);
        } catch (error) {
            setLoading(false);
        }
    };

    //初始化数据
    useEffect(() => {
        fetch(paginationRef.current);
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    //改变页面
    const changePagination = (paginationParams: Pagination.paginationProps) => {
        paginationRef.current = {
            ...paginationRef.current,
            ...paginationParams,
        };
        fetch(paginationRef.current);
    };

    //重置分页
    const resertPagination = () => {
        paginationRef.current = {
            ...paginationRef.current,
            current: 1,
        };
        fetch(paginationRef.current);
    };

    const tableProps: Pagination.TableProps = {
        loading,
        dataSource,
        onChange: changePagination,
        pagination: paginationRef.current,
    };

    return {
        tableProps,
        search: resertPagination,
    };
}
